//引入“userDao”依赖
const UserDao=require("../../dao/user/user_dao.js");

//业务流程
const UserService={
	//注册
	register(req,res,next){
		//POST请求方式获取数据
		const {username,password}=req.body;
		UserDao.save({username,password})
				.then((data)=>{
					req.session.loginUser=username;

					res.json({res_code:1,res_error:"",res_body:{status:1,message:"success",data:{username:data.username}}});
				})
				.catch((err)=>{
					console.log(err);
					res.json({res_code:1,res_error:"",res_body:{status:0,message:"failed:"+err,data:{}}});
				});
	},
	//登录
	login(req,res,next){
		const {username,password}=req.body;
		//数据访问
		UserDao.find({username})
		.then((data)=>{
			if (data.length===1){
				if (password===data[0].password){
					req.session.loginUser = username;

					res.json({
						res_code:1,
						res_error:"",
						res_body:{
							status:1,
							message:"success",
							data:{
								username:data[0].username
							}
						}});
			}else {//密码不一致
				res.json({
						res_code:1,
						res_error:"",
						res_body:{
							status:0,
							message:"密码错误",
							data:{}
						}});
			}
			res.json();
		}else{// 不存在与查找用户名相关的对象
			res.json({
				res_code: 1,
				res_error:"",
				res_body: {
					status: 0,
					message: "用户名不存在",
					data: {}
				}});
			}
		})
		.catch((err)=>{
			res.json({
				res_code: 0,
				res_error: err,
				res_body: {}
			});
		});
	},
	//注销
	logout(req,res,next){
		req.session.loginUser = null;
		res.json({
			res_code: 1,
			res_error: "",
			res_body: {
				status: 1
			}
		})
	}
}

module.exports=UserService;